package com.lwq.util;

import java.lang.reflect.Type;
import java.text.DateFormat;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonUtil {
	public final static int DEFAULT_TYPE = 0;
	public final static int BUILD_TYPE = 1;
	public int mType = DEFAULT_TYPE;
	private Gson defGson = null;
	private Gson buildGson = null;
	private static GsonUtil instance = null;
	
	public GsonUtil(int type) {
		mType = type;
		if (mType == DEFAULT_TYPE) {
			defGson = new Gson();
		} else if (mType == BUILD_TYPE) {
			buildGson  = new GsonBuilder()  
		        .excludeFieldsWithoutExposeAnnotation() 
		        .enableComplexMapKeySerialization() 
		        .serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
		        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
		        .setPrettyPrinting() 
		        .setVersion(1.0)   
		        .create(); 
		}
	}

	public static GsonUtil getInstance(int type) {
		if(instance == null){
			instance = new GsonUtil(type);
		}
		if(instance .mType != type){
			instance = new GsonUtil(type);
		}
		return instance;
	}
	/**
	 * 把json字符串解析成指定的Type
	 * 
	 * @param json
	 *            需要解析的json字符串
	 * @param typeOfT
	 *            指定需要解析的类型
	 */
	public <T> T jsonToModel(String json, Type typeOfT) {
		if(mType == DEFAULT_TYPE){
			return defGson.fromJson(json, typeOfT);
		}else if(mType == BUILD_TYPE){
			return buildGson.fromJson(json, typeOfT);
		}
		return null;
	}

	public <T> T FileToModel(String path, Type typeOfT) {
		String json = (String) FileUtil.readFileData(path, 0, FileUtil.FILEEND,
				FileUtil.DATATYPE_STRING);
		return jsonToModel(json, typeOfT);
	}

	/**
	 * 把指定的type型转化为json字符串
	 * 
	 * @param itemContent
	 * @return
	 */
	public String modelToJson(Object typeOfT) {
		
		if(mType == DEFAULT_TYPE){
			return defGson.toJson(typeOfT);
		}else if(mType == BUILD_TYPE){
			return buildGson.toJson(typeOfT);
		}
		return null;
		
	}

	public void modelToFile(Object typeOfT, String path) {
		String json = modelToJson(typeOfT);
		FileUtil.writeFileData(path, json);
	}
}